package com.gxa.meiye.sso.service.impl;

import com.baomidou.mybatisplus.generator.IFill;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.exception.ExceptionCode;
import com.gxa.meiye.core.pojo.vo.TherapistLoginInfo;
import com.gxa.meiye.sso.repository.TherapistRepository;
import com.gxa.meiye.sso.service.TherapistService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
@Transactional(rollbackFor = Throwable.class)
public class TherapistServiceImp implements TherapistService {
    //给token添加一个标签
    private static final String SALT = "ASUKA_LANGLY:";
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    TherapistRepository therapistRepository;
    @Autowired
    HttpServletRequest httpServletRequest;

    @Override
    public String login(String phone, String code) throws BusinessException, JsonProcessingException {
        //1.获取redis中保存的验证码
        Object redisCode = redisTemplate.opsForValue().get(SMServiceImp.LOGIN_SMS + phone);
        System.out.println(redisCode);
        //判断验证码失效的情况
        if (StringUtils.isEmpty(redisCode)) {
            throw new BusinessException(ExceptionCode.EXPIRE_CODE);
        }
        if (!code.equals(redisCode)) {
            throw new BusinessException(ExceptionCode.WRONG_CODE);
        }
        //验证码验证完成后，删除redis中的验证码
        redisTemplate.delete(SMServiceImp.LOGIN_SMS + phone);
        //从数据库中获取对象
        TherapistLoginInfo findTherapist = therapistRepository.findByPhone(phone);
        System.out.println(findTherapist);
        //新用户注册
        if (findTherapist == null) {
            findTherapist = new TherapistLoginInfo();
            //用户的号码
            findTherapist.setPhone(phone);
            findTherapist.setName("therapist" + phone);
            //身份状态信息
            findTherapist.setStatus("1");
        }
        //老用户登录
        //如果当前用户存在，则删除当前的token,防止重复登录
        String lasttoken = findTherapist.getToken();
        redisTemplate.delete(SALT+lasttoken);
            //将标签与生成的uuid最为token的key；
            String token = UUID.randomUUID().toString().replace("-", "");
            findTherapist.setToken(token);
            String key = (SALT+token);
            //登陆完成后保存信息到数据库
        TherapistLoginInfo save = therapistRepository.save(findTherapist);
        //将包含用户信息的key保存到redis,将save对象生成json，并将生成的json作为String
            ObjectMapper objectMapper = new ObjectMapper();
            String userValue = objectMapper.writeValueAsString(save);
        System.out.println(userValue);
            Integer expire = 24*30*2;
            //设置token的过期时间 2个月
            redisTemplate.opsForValue().set(key, userValue,expire,TimeUnit.HOURS);
            //返回token
        return token;

}

    @Override
    public TherapistLoginInfo queryUserByToken(String token) throws BusinessException, JsonProcessingException {
        //从redis中取出用户信息
        String key = SALT+token;
        //取出token信息
         Object data = redisTemplate.opsForValue().get(key);
        System.out.println(data);
        //TOKEN不存在，抛出异常
        if(StringUtils.isEmpty(data)){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        //将redis中保存的用户信息转换为user对象并返回
        ObjectMapper objectMapper = new ObjectMapper();
        TherapistLoginInfo therapistLoginInfo = objectMapper.readValue(data.toString(), TherapistLoginInfo.class);
        System.out.println(therapistLoginInfo);
        return therapistLoginInfo;

    }
}
